package vip.redme.memory.context;

import vip.redme.memory.pojo.entity.User;
import vip.redme.memory.util.Args;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户信息上下文
 *
 * @author HUZHAOYANG
 * @version 1.0
 * @date 2021/4/23 14:35
 */
public class UserContext {


    /**
     * tokenKey
     */
    public static final String CONTEXT_KEY_USER_TOKEN = "token";
    /**
     * 用户idKey
     */
    public static final String CONTEXT_KEY_USER_ID = "userId";
    /**
     * 用户user key
     */
    public static final String CONTEXT_KEY_USER = "user";
    private static ThreadLocal<Map<String, Object>> threadLocal;

    static {
        threadLocal = new ThreadLocal<>();
    }

    /**
     * 设置数据
     *
     * @param key   键
     * @param value 值
     */
    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>(6);
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    /**
     * 获取数据
     *
     * @param key 键
     * @return 值
     */
    @SuppressWarnings("checked")
    public static <T> T get(String key) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>();
            threadLocal.set(map);
        }
        Object value = map.get(key);
        return Args.isNull(value) ? null : (T) value;
    }

    /**
     * 清除数据
     */
    public static void remove() {
        threadLocal.remove();
    }

    public static Long getUserId() {
        return get(CONTEXT_KEY_USER_ID);
    }

    public static void setUserId(Long userId) {
        set(CONTEXT_KEY_USER_ID, userId);
    }

    public static String getToken() {
        return get(CONTEXT_KEY_USER_TOKEN);
    }

    public static void setToken(String token) {
        set(CONTEXT_KEY_USER_TOKEN, token);
    }

    public static User getUser() {
        return get(CONTEXT_KEY_USER);
    }

    public static void setUser(User user) {
        set(CONTEXT_KEY_USER, user);
    }

}
